﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace DotNet.Utilities.Mail
{
    /// <summary>
    ///Smtp 的摘要说明
    /// </summary>
    public class Smtp
    {
        public Smtp()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 通过smtp直接发送邮件
        /// </summary>
        /// <param name="toEmail">收件箱地址</param>
        /// <param name="toDisplayName">发件人名称</param>
        /// <param name="subject">标题</param>
        /// <param name="body">内容</param>
        /// <param name="toBcc">密文抄送列表</param>
        /// <param name="toCc">抄送列表</param>
        /// <returns></returns>
        public static bool SenMailBySMTP(string toEmail, string toDisplayName, string toCc, string toBcc, string subject, string body, string UserName, string PassWord)
        {
            //string toEmail, string toCCMail, string toBCCMail, string strToName, string strFromName, string strContent, string strTitle, string strContentType, string strFiles

            string fromEmail = UserName; //ConfigurationManager.AppSettings["mailusername"].ToString();//发件箱地址
            string fromDisplayName = toDisplayName; //ConfigurationManager.AppSettings["FromName"].ToString();//显示的发件人名称
            string pwd = PassWord; //ConfigurationManager.AppSettings["mailpassword"].ToString();//发件箱密码
            string smtpAddress = string.Format("smtp.{0}", UserName.Substring(UserName.IndexOf("@") + 1)); //ConfigurationManager.AppSettings["mailSmtpHost"].ToString();//smtp host


            //邮件
            MailMessage mail = new MailMessage();

            //发件人地址
            mail.From = new MailAddress(fromEmail, fromDisplayName);

            //收件人地址
            if (toEmail.Length > 0)
                mail.To.Add(toEmail);
            else return false;

            //抄送人
            if (toCc.Length > 0)
                mail.CC.Add(toCc);

            //密送
            if (toBcc.Length > 0)
                mail.Bcc.Add(toBcc);

            //mail.s
            mail.SubjectEncoding = Encoding.UTF8;
            mail.Subject = subject;
            mail.IsBodyHtml = true; //是否允许内容为 HTML 格式
            mail.BodyEncoding = Encoding.UTF8;
            mail.Body = body;
            //mail.Attachments.Add(new Attachment("E:\\99.jpg")); //添加一个附件

            SmtpClient smtp = new SmtpClient(smtpAddress);
            smtp.Credentials = new NetworkCredential(fromEmail, pwd); //SMTP 验证

            bool rr = true;

            try
            {
                smtp.Send(mail);
            }
            catch
            {
                rr = false;
            }

            mail.Attachments.Dispose(); //邮件发送完毕，释放对附件的锁定

            return rr;

        }
    }
}
